<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="app"></div>
    <script src="https://unpkg.com/@vue/reactivity@3.0.5/dist/reactivity.global.js"></script>

    <script>
        const { effect, ref } = VueReactivity


        function createRenderer(options) {
            const {
                createElement,
                insert,
                setElementText
            } = options

            function mountElement(vnode, container) {
                // type
                const el = createElement(vnode.type)
                // children
                if (typeof vnode.children === "string") {
                    setElementText(el, vnode.children)
                } else if (Array.isArray(vnode.children)) {
                    vnode.children.forEach(child => {
                        patch(null, child, el)
                    });
                }
                // props
                if (vnode.props) {
                    for (const key in vnode.props) {
                        el.setAttribute(key, vnode.props[key])
                    }
                }
                insert(el, container)
            }

            function patch(n1, n2, container) {
                if (!n1) {
                    mountElement(n2, container)
                } else {

                }
            }

            function render(vnode, container) {
                if (vnode) {
                    // 新node 打补丁
                    patch(container._vnode, vnode, container)
                } else {
                    if (container._vnode) {
                        container.innerHTML = ''
                    }
                }

                // 记录旧的vnode
                container._vnode = vnode
            }

            return {
                render
            }
        }

        const vnode = {
            type: 'div',
            props: {
                id: 'foo'
            },
            children: [
                {
                    type: 'p',
                    children: 'hello'
                }
            ]
        }
        const renderer2 = createRenderer({
            createElement(tag) {
                console.log(`创建元素 ${tag}`)
                return { tag }
            },
            setElementText(el, text) {
                console.log(`设置 ${JSON.stringify(el)} 的文本内容：${text}`)
                el.text = text
            },
            insert(el, parent, anchor = null) {
                console.log(`将 ${JSON.stringify(el)} 添加到 ${JSON.stringify(parent)} 下`)
                parent.children = el
            }
        })

        const container = { type: 'root' }
        renderer2.render(vnode, container)

    </script>
</body>

</html>